package com.zzyl.nursing.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.nursing.service.IWechatService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @author wys
 * @version V1.0
 * @date 2025-03-03 17:06
 */
@Service
public class WechatServiceImpl implements IWechatService {

    @Value("${wechat.appid}")
    private String appid;

    @Value("${wechat.secret}")
    private String secret;

    // 登录
    private final String REQUEST_URL = "https://api.weixin.qq.com/sns/jscode2session";

    // 获取token
    private static final String TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential";

    // 获取手机号
    private final String PHONE_REQUEST_URL = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=";

    @Override
    public String getOpenid(String code) {
        Map<String, Object> map = getAppConfig();
        map.put("js_code", code);
        String result = HttpUtil.get(REQUEST_URL, map);
        if (StrUtil.isBlank(result)) {
            throw new BaseException("Openid获取失败");
        }
        JSONObject jsonObject = JSONUtil.parseObj(result);
        if (ObjectUtil.isNotEmpty(jsonObject.get("errcode"))) {
            throw new BaseException(jsonObject.getStr("errmsg"));
        }
        return jsonObject.getStr("openid");
    }

    @Override
    public String getPhoneNumber(String code) {
        String token = getToken();
        Map<String, String> map = Map.of("code", code);
        String jsonStr = JSONUtil.toJsonStr(map);
        String result = HttpUtil.post(PHONE_REQUEST_URL + token, jsonStr);
        if (StrUtil.isBlank(result)) {
            throw new BaseException(" 手机号获取失败");
        }
        JSONObject jsonObject = JSONUtil.parseObj(result);
        if (jsonObject.getInt("errcode") != 0) {
            throw new BaseException(jsonObject.getStr("errmsg"));
        }
        return jsonObject.getJSONObject("phone_info").getStr("phoneNumber");
    }

    private String getToken() {
        Map<String, Object> map = getAppConfig();
        String result = HttpUtil.get(TOKEN_URL, map);
        if (StrUtil.isBlank(result)) {
            throw new BaseException("Token获取失败");
        }
        JSONObject jsonObject = JSONUtil.parseObj(result);
        if (ObjectUtil.isNotEmpty(jsonObject.get("errcode"))) {
            throw new BaseException(jsonObject.getStr("errmsg"));
        }
        return jsonObject.getStr("access_token");
    }

    private Map<String, Object> getAppConfig() {
        Map<String, Object> map = new HashMap<>();
        map.put("appid", appid);
        map.put("secret", secret);
        return map;
    }
}
